<template>
  <view class="page-container">
    <!-- 搜索栏 -->
    <view class="search-bar">
      <uni-easyinput
        prefixIcon="search"
        v-model="queryParams.keyword"
        placeholder="请输入活动名称"
        @confirm="handleSearch"
        :inputBorder="false"
        class="search-input"
      ></uni-easyinput>
    </view>

    <!-- 状态筛选标签 -->
    <view class="tabs-container">
      <view
        v-for="tab in activityStatusTabs"
        :key="tab.value"
        class="tab-item"
        :class="{ active: queryParams.status === tab.value }"
        @click="handleTabChange(tab.value)"
      >
        {{ tab.label }}
      </view>
    </view>

    <!-- 活动列表 -->
    <scroll-view scroll-y class="list-scroll" @scrolltolower="handleScrollToLower">
      <view v-if="!loading && activities.length === 0" class="empty-container">
        <uni-icons type="folder-opened" size="60" color="#ccc"></uni-icons>
        <text class="empty-text">暂无活动</text>
      </view>
      <view v-else>
        <view v-for="activity in activities" :key="activity.id" class="activity-card" @click="goToDetail(activity.id)">
          <view class="card-header">
            <text class="activity-name">{{ activity.name }}</text>
            <uni-tag 
              :text="getActivityStatusText(activity.status)" 
              :type="getActivityStatusType(activity.status)" 
              size="small"
            ></uni-tag>
          </view>
          <view class="card-body">
            <view class="activity-info">
              <view class="info-row">
                <uni-icons type="calendar" size="14" color="#999"></uni-icons>
                <text class="info-text">{{ formatTime(activity.start_time) }} 至 {{ formatTime(activity.end_time) }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="person" size="14" color="#999"></uni-icons>
                <text class="info-text">参与人数: {{ activity.participant_count || 0 }}</text>
              </view>
              <view class="info-row">
                <uni-icons type="gift" size="14" color="#999"></uni-icons>
                <text class="info-text">发放数量: {{ activity.issued_count || 0 }}</text>
              </view>
            </view>
          </view>
          <view class="card-footer">
            <text class="activity-desc">{{ activity.description || '暂无描述' }}</text>
            <view class="action-buttons">
              <button 
                class="action-btn edit-btn" 
                size="mini" 
                @click.stop="editActivity(activity.id)"
              >
                编辑
              </button>
              <button 
                class="action-btn" 
                :class="activity.status === 1 ? 'disable-btn' : 'enable-btn'"
                size="mini" 
                @click.stop="toggleActivityStatus(activity)"
              >
                {{ activity.status === 1 ? '禁用' : '启用' }}
              </button>
            </view>
          </view>
        </view>
      </view>
      <uni-load-more :status="loadMoreStatus"></uni-load-more>
    </scroll-view>

    <!-- 浮动添加按钮 -->
    <view class="fab-container">
      <view class="fab-button" @click="goToDetail()">
        <uni-icons type="plusempty" size="24" color="#fff"></uni-icons>
      </view>
    </view>
  </view>
</template>

<script setup lang="ts">
import { ref, reactive } from 'vue';
import { onPullDownRefresh, onReachBottom, onLoad } from '@dcloudio/uni-app';
import { fetchCouponActivities, updateActivityStatus } from '@/api/coupon';
import moment from 'moment';

// 活动状态枚举
enum ActivityStatus {
  Draft = 0,    // 草稿
  Active = 1,   // 进行中
  Ended = 2,    // 已结束
  Disabled = 3  // 已禁用
}

interface CouponActivity {
  id: number;
  name: string;
  description?: string;
  start_time: number;
  end_time: number;
  status: ActivityStatus;
  participant_count?: number;
  issued_count?: number;
  created_at: number;
  updated_at: number;
}

interface ActivityQuery {
  page: number;
  pageSize: number;
  keyword?: string;
  status?: ActivityStatus;
}

const activities = ref<CouponActivity[]>([]);
const loading = ref(true);
const queryParams = reactive<ActivityQuery>({
  page: 1,
  pageSize: 10,
  keyword: '',
  status: undefined,
});
const total = ref(0);
const loadMoreStatus = ref('more');

const activityStatusTabs = [
  { label: '全部', value: undefined },
  { label: '进行中', value: ActivityStatus.Active },
  { label: '已结束', value: ActivityStatus.Ended },
  { label: '草稿', value: ActivityStatus.Draft },
  { label: '已禁用', value: ActivityStatus.Disabled },
];

const getActivities = async (isRefresh = false) => {
  if (isRefresh) {
    queryParams.page = 1;
  }
  loadMoreStatus.value = 'loading';
  try {
    const res = await fetchCouponActivities(queryParams);
    if (isRefresh) {
      activities.value = res.list;
    } else {
      activities.value = [...activities.value, ...res.list];
    }
    total.value = res.total;
    if (activities.value.length >= total.value) {
      loadMoreStatus.value = 'noMore';
    } else {
      loadMoreStatus.value = 'more';
    }
  } catch (error) {
    console.error('获取活动列表失败:', error);
    loadMoreStatus.value = 'more';
    uni.showToast({
      title: '获取活动列表失败',
      icon: 'none'
    });
  } finally {
    loading.value = false;
    uni.stopPullDownRefresh();
  }
};

const handleSearch = () => {
  getActivities(true);
};

const handleTabChange = (status: ActivityStatus | undefined) => {
  queryParams.status = status;
  getActivities(true);
};

const handleScrollToLower = () => {
  if (loadMoreStatus.value === 'more') {
    queryParams.page = (queryParams.page || 1) + 1;
    getActivities();
  }
};

const goToDetail = (id?: number) => {
  const url = id ? `/pages/coupons/activity/detail?id=${id}` : '/pages/coupons/activity/detail';
  uni.navigateTo({ url });
};

const editActivity = (id: number) => {
  uni.navigateTo({
    url: `/pages/coupons/activity/detail?id=${id}&mode=edit`
  });
};

const toggleActivityStatus = async (activity: CouponActivity) => {
  const newStatus = activity.status === ActivityStatus.Active ? ActivityStatus.Disabled : ActivityStatus.Active;
  const actionText = newStatus === ActivityStatus.Active ? '启用' : '禁用';
  
  uni.showModal({
    title: '确认操作',
    content: `确定要${actionText}此活动吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          await updateActivityStatus(activity.id, newStatus);
          activity.status = newStatus;
          uni.showToast({
            title: `${actionText}成功`,
            icon: 'success'
          });
        } catch (error) {
          console.error(`${actionText}活动失败:`, error);
          uni.showToast({
            title: `${actionText}失败`,
            icon: 'none'
          });
        }
      }
    }
  });
};

const getActivityStatusText = (status: ActivityStatus) => {
  const statusMap = {
    [ActivityStatus.Draft]: '草稿',
    [ActivityStatus.Active]: '进行中',
    [ActivityStatus.Ended]: '已结束',
    [ActivityStatus.Disabled]: '已禁用'
  };
  return statusMap[status] || '未知';
};

const getActivityStatusType = (status: ActivityStatus) => {
  const typeMap = {
    [ActivityStatus.Draft]: 'default',
    [ActivityStatus.Active]: 'success',
    [ActivityStatus.Ended]: 'warning',
    [ActivityStatus.Disabled]: 'error'
  };
  return typeMap[status] || 'default';
};

const formatTime = (timestamp: number) => {
  return moment(timestamp * 1000).format('MM-DD HH:mm');
};

onLoad(() => {
  getActivities(true);
});

onPullDownRefresh(() => {
  getActivities(true);
});

onReachBottom(() => {
  handleScrollToLower();
});
</script>

<style lang="scss" scoped>
.page-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: var(--background-color);
}

.search-bar {
  padding: 10px;
  background-color: #fff;
  .search-input {
    background-color: var(--background-color);
    border-radius: var(--border-radius-lg);
  }
}

.tabs-container {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid var(--border-color);
  .tab-item {
    flex: 1;
    text-align: center;
    padding: 12px 0;
    font-size: 14px;
    color: var(--text-color-secondary);
    position: relative;
    &.active {
      color: var(--primary-color);
      font-weight: bold;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 50%;
        transform: translateX(-50%);
        width: 30px;
        height: 3px;
        background-color: var(--primary-color);
        border-radius: 2px;
      }
    }
  }
}

.list-scroll {
  flex: 1;
  height: 0;
}

.activity-card {
  background-color: #fff;
  margin: 10px;
  border-radius: var(--border-radius);
  padding: 15px;
  box-shadow: var(--shadow);
  
  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-bottom: 10px;
    border-bottom: 1px solid var(--border-color);
    .activity-name {
      font-size: 16px;
      font-weight: bold;
      color: var(--text-color-primary);
    }
  }
  
  .card-body {
    padding: 15px 0;
    .activity-info {
      .info-row {
        display: flex;
        align-items: center;
        margin-bottom: 8px;
        .info-text {
          font-size: 12px;
          color: var(--text-color-secondary);
          margin-left: 8px;
        }
      }
    }
  }
  
  .card-footer {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding-top: 10px;
    border-top: 1px solid var(--border-color);
    .activity-desc {
      font-size: 12px;
      color: var(--text-color-secondary);
      flex: 1;
      margin-right: 10px;
      overflow: hidden;
      text-overflow: ellipsis;
      white-space: nowrap;
    }
    .action-buttons {
      display: flex;
      gap: 8px;
      .action-btn {
        padding: 4px 12px;
        font-size: 12px;
        border-radius: 4px;
        border: none;
        &.edit-btn {
          background-color: #1890ff;
          color: #fff;
        }
        &.enable-btn {
          background-color: #52c41a;
          color: #fff;
        }
        &.disable-btn {
          background-color: #ff4d4f;
          color: #fff;
        }
      }
    }
  }
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding-top: 100px;
  .empty-text {
    margin-top: 15px;
    color: #999;
  }
}

.fab-container {
  position: fixed;
  right: 20px;
  bottom: 40px;
  .fab-button {
    width: 50px;
    height: 50px;
    border-radius: 50%;
    background-color: var(--primary-color);
    display: flex;
    align-items: center;
    justify-content: center;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  }
}
</style>